import traceback
from typing import Generic, Any, final, List
from aiohttp import web

from . import JsonEndpointDescriptor
from ..jsonpat.typescript_presentation import to_typescript_plain_text
from .request_handler import HttpEndpointDescriptor


def generate_documentation_handler(descriptors: List[HttpEndpointDescriptor]):
    lines = []
    for descriptor in descriptors:
        lines.append(f'**{descriptor.method}** `{descriptor.path}`')
        lines.append("")
        if isinstance(descriptor, JsonEndpointDescriptor):
            in_body_type, in_query_type, out_type = descriptor.types
            try:
                if in_query_type is not None:
                    lines.append("Url Params 格式:")
                    lines.append("")
                    lines.append("```typescript")
                    lines.append(to_typescript_plain_text(in_query_type))
                    lines.append("```")
                    lines.append("")

                if in_body_type is not None:
                    lines.append("Request Body 格式:")
                    lines.append("")
                    lines.append("```typescript")
                    lines.append(to_typescript_plain_text(in_body_type))
                    lines.append("```")
                    lines.append("")

                lines.append("Response Body 格式:")
                lines.append("")
                lines.append("```typescript")
                lines.append(to_typescript_plain_text(out_type))
                lines.append("```")
            except:
                lines.append(f"<出错了> {traceback.format_exc()}")

        lines.append("")
        lines.append("-" * 50)
        lines.append("")
    resp_body = "\n".join(lines)

    async def on_request(request: web.Request) -> web.Response:
        if request.rel_url.query_string == "kan_wen_dang_1234":
            return web.Response(body=resp_body.encode("utf8"), content_type="text/plain", charset="utf8")
        else:
            return web.Response(body=f"wrong query: {request.rel_url.query_string}", status=404)

    return on_request
